<template>
  <ContentBase>
    <a-row>
      <a-col :span="1" style="margin-right: 15px">
        <a-button type="primary" ghost @click="onInsert">新增</a-button>
      </a-col>
      <a-col :span="3">
        <a-popconfirm
          title="确认要删除选中学生吗?"
          ok-text="确定"
          cancel-text="取消"
          @confirm="onDeleteIds"
          @visibleChange="onVisibleChange"
          :visible="visible"
        >
          <a-button type="primary" ghost>删除选中</a-button>
        </a-popconfirm>
      </a-col>
      <a-col :span="4">
        <a-upload
          :before-upload="beforeUpload"
          :multiple="false"
          :show-upload-list="false"
          accept=".xls,.xlsx"
        >
          <a-button class="uploadfile">
            <span>上传知识</span><UploadOutlined />
          </a-button>
        </a-upload>
      </a-col>
      <a-col :span="4"> </a-col>
      <a-col :span="5"></a-col>
      <a-col :span="4" style="margin-right: 5px">
        <a-input v-model:value="searchKeyword" placeholder="请输入搜索内容"
          ><template #prefix> <search-outlined /> </template
        ></a-input>
      </a-col>
      <a-col :span="2">
        <a-button @click="handleSearch" type="primary" ghost>搜索</a-button>
      </a-col>
    </a-row>
    <hr />
    <a-row
      ><a-col :span="23">
        <a-table
          :row-selection="{ selectedRowKeys: ids, onChange: onSelectChange }"
          :columns="columns"
          :data-source="pagedDataSource"
          :height="tableHeight"
          :scroll="{ y: tableHeight }"
          :pagination="{
            current: currentPage,
            pageSize: pageSize,
            total: totalRecords2,
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total, range) =>
              `${range[0]}-${range[1]} 共 ${total} 条`,
            showLessItems: true,
            pageSizeOptions: ['5', '8', '10', '20'],
            onChange: handlePageChange,
            onShowSizeChange: handlePageSizeChange,
            locale: {
              items_per_page: '条/页',
              jump_to: '跳至',
              jumper_page: '页',
              prev_page: '上一页',
              next_page: '下一页',
              prev_5: '向前5页',
              next_5: '向后5页',
              prev_3: '向前3页',
              next_3: '向后3页',
            },
          }"
          bordered
        >
          <template #bodyCell="{ column, text, record }">
            <template
              v-if="
                ['key', 'source', 'creator', 'time'].includes(column.dataIndex)
              "
            >
              <!-- <div>
          <a-input
            v-if="editableData[record.key]"
            v-model:value="editableData[record.key][column.dataIndex]"
            style="margin: -5px 0"
          />
          <template v-else>
            {{ text }}
          </template>
        </div> 定制编辑状态的数据行格式，这里并不需要,编辑时会单独弹窗  -->
              {{ text }}
            </template>
            <template v-else-if="column.key === 'content'">
              <span>{{ truncateString(text) }}</span>
            </template>
            <template v-else-if="column.dataIndex === 'operation'">
              <div class="operations">
                <span>
                  <a-typography-link
                    @click="detail(record.key)"
                    style="margin-right: 8px"
                    >详情</a-typography-link
                  >
                  <a-typography-link
                    @click="edit(record.key)"
                    style="margin-right: 8px"
                    >编辑</a-typography-link
                  >
                  <a-popconfirm
                    title="确认删除?"
                    ok-text="确认"
                    cancel-text="取消"
                    @confirm="deleteSingle(record.key)"
                  >
                    <a-typography-link>删除</a-typography-link>
                  </a-popconfirm>
                </span>
              </div>
            </template>
            <template v-else>
              {{ text }}
            </template>
          </template>
        </a-table>
      </a-col>
      <a-col :span="1"></a-col>
    </a-row>
    <EditSave
      v-model:id="id"
      :dto="saveDto"
      v-model:visible="saveVisible"
      @saved="onSaved"
      @insertFinish="onInsertFinish"
    ></EditSave>
    <!-- <a-table :dataSource="dataSource" :columns="columns" :row-key="id"/> -->
  </ContentBase>
</template>

<script setup>
import ContentBase from "../ContentBase.vue";
import EditSave from "./EditSave.vue";
import { formatCurrentTime, columns, data } from "@/tools/knowledgeCals.js";
import {
  ref,
  reactive,
  computed,
  toRefs,
  watchEffect,
  onMounted,
  onUnmounted,
} from "vue";
import { cloneDeep } from "lodash-es";
import { UploadOutlined, SearchOutlined } from "@ant-design/icons-vue";
import * as XLSX from "xlsx";
import { message } from "ant-design-vue";

const maxKey = ref(data.length);

const saveVisible = ref(false);
const id = ref(0); // flag 当且仅当为 0 时显示插入
const ids = ref([]); // 存放选择列表
const dataSource = ref(data);
const editableData = reactive({});
const saveDto = reactive({}); // 数据编辑时存储
// 分页功能
const dto = ref({ page: 1, size: 5, source: "", creator: "", content: "" });

const tableHeight = ref(420);

function onSelectChange(keys) {
  console.log(keys);
  ids.value = keys;
}

function truncateString(str) {
  //字符串截断函数
  return str.length > 25 ? str.substring(0, 25) + "......" : str;
}

const detail = (key) => {
  id.value = -1;
  saveVisible.value = true;

  Object.assign(
    saveDto,
    cloneDeep(dataSource.value.filter((item) => key === item.key)[0])
  );
};

const edit = (key) => {
  id.value = dataSource.value.filter((item) => key === item.key)[0].key;
  saveVisible.value = true;
  editableData[key] = cloneDeep(
    dataSource.value.filter((item) => key === item.key)[0]
  );
  Object.assign(saveDto, editableData[key]);
};

const deleteSingle = (key) => {
  delete editableData[key];
  dataSource.value = dataSource.value.filter((item) => item.key !== key);
  filteredData.value = filteredData.value.filter((item) => item.key !== key);
  loadPagedData(filteredData);
  message.success("删除成功");
};
function onSaved(cdata) {
  // search(dto.value) 查询数据库获取新视图
  Object.assign(saveDto, cdata);
  editableData[cdata.key] = cdata;
  Object.assign(
    dataSource.value.filter((item) => item.key === cdata.key)[0],
    cdata
  );
  console.log("查询数据库获取新数据视图");
}
function onInsert() {
  saveVisible.value = true;
  id.value = 0;
  Object.assign(saveDto, {
    key: maxKey.value.toString(),
    source: "",
    creator: "",
    content: "",
    time: formatCurrentTime(),
  });
}

function onInsertFinish(cdata) {
  maxKey.value += 1;
  // dataSource.value.push(cdata) // 错误，每次修改的是同一对象的引用
  dataSource.value.push(cloneDeep(cdata));
  filteredData.value.push(cloneDeep(cdata));
  loadPagedData(filteredData);
  message.success("新增成功");
}

function onUpdate(record) {
  saveVisible.value = true;
  id.value = record.key; // 非0即可
  // saveDto.value.source = record.source
  // saveDto.value.sex = record.sex
  // saveDto.value.creator = record.creator
  Object.assign(saveDto, record);
}

const visible = ref(false);
function onVisibleChange(v) {
  // 传入boolean值
  if (!v) {
    // 希望隐藏
    visible.value = false;
  } else {
    // 希望显示
    visible.value = ids.value.length > 0;
  }
}

function onDeleteIds() {
  dataSource.value = dataSource.value.filter(
    (item) => !ids.value.includes(item.key)
  );
  filteredData.value = filteredData.value.filter(
    (item) => !ids.value.includes(item.key)
  );
  loadPagedData(filteredData);
  ids.value = [];
  message.success("删除成功");
}

// 分页
const pagedDataSource = ref([]);

// 分页相关变量
const currentPage = ref(1);
const pageSize = ref(8);

const { dataSource: dataSourceRef } = toRefs({ dataSource });
const totalRecords = ref(dataSourceRef.value.length); // ref不会触发需要依赖ref计算的属性，因此用toRefs
watchEffect(() => {
  totalRecords.value = dataSourceRef.value.length;
});

// 处理分页变化
function handlePageChange(page, psize) {
  currentPage.value = page;
  pageSize.value = psize;
  loadPagedData(filteredData);
}

// 处理每页数量变化
function handlePageSizeChange(current, size) {
  pageSize.value = size;
  loadPagedData(filteredData);
}

// 加载分页数据
function loadPagedData(curdata) {
  const start = (currentPage.value - 1) * pageSize.value;
  const end = start + pageSize.value;
  pagedDataSource.value = curdata.value.slice(start, end);
}

// 调用loadPagedData初始化分页数据
const filteredData = ref([]);
filteredData.value = dataSource.value;
const { filteredData: filteredDataRef } = toRefs({ filteredData });
const totalRecords2 = ref(filteredDataRef.value.length); // ref不会触发需要依赖ref计算的属性，因此用toRefs
watchEffect(() => {
  totalRecords2.value = filteredDataRef.value.length;
});

// 搜索处理
const searchKeyword = ref("");

function handleSearch() {
  updateFilteredData();
  loadPagedData(filteredData);
}

// 根据关键词更新过滤数据
function updateFilteredData() {
  const keyword = searchKeyword.value?.trim();
  if (keyword) {
    filteredData.value = dataSource.value.filter((record) => {
      return (
        record.creator.toLowerCase().includes(keyword) ||
        record.content.toLowerCase().includes(keyword)
      );
    });
  } else {
    // 如果没有搜索关键词，则显示所有数据
    filteredData.value = dataSource.value;
  }
}

// 上传数据
// 文件上传前处理
const beforeUpload = (file) => {
  filteredData.value = dataSource.value;
  handleFile(file);
  // message.success("上传成功");
  return false; // 阻止默认上传行为
};

onMounted(() => {
  loadPagedData(filteredData);
  document.body.style.overflowY = "hidden";
  // 添加一个清理函数，例如当组件被销毁时恢复滚动条
  return () => {
    document.body.style.overflowY = "";
  };
});

onUnmounted(() => {
  // 仅当前页面禁止document的滚动条
  document.body.style.overflowY = "";
});

// 处理文件
const handleFile = async (file) => {
  const fileReader = new FileReader();
  fileReader.onload = (e) => {
    const binaryStr = e.target.result;
    const workbook = XLSX.read(binaryStr, { type: "binary" });
    const sheetName = workbook.SheetNames[0];
    const sheet = workbook.Sheets[sheetName];
    const parsedData = XLSX.utils.sheet_to_json(sheet, { header: 1 });

    // 将第一行作为表头
    const headers = parsedData[0];
    if (validateData(headers)) {
      if (parsedData.length > 0) {
        const headers = parsedData.shift();

        // 转换数据格式
        let keyCounter = dataSource.value.length - 1;
        const transformedData = parsedData.map((row) => {
          keyCounter++;
          return {
            key: keyCounter.toString(),
            source: row[headers.indexOf("source")],
            creator: row[headers.indexOf("creator")],
            content: row[headers.indexOf("content")],
            time: row[headers.indexOf("time")],
          };
        });

        // 更新数据源
        // data.value = transformedData; // ref 数据
        dataSource.value = dataSource.value.concat(transformedData);
        filteredData.value = filteredData.value.concat(transformedData);
      }
    } else {
      message.error("数据格式不符合要求");
    }
  };

  fileReader.readAsBinaryString(file);
};

// 数据验证函数
function validateData(headers) {
  if (!headers || headers.length !== 4) {
    return false; // 表头数量不符合要求
  }

  const requiredHeaders = ["source", "creator", "content", "time"];
  console.log(headers, requiredHeaders);

  // 检查所有必需的列是否存在
  console.log(requiredHeaders.every((header) => headers.includes(header)));
  return requiredHeaders.every((header) => headers.includes(header));
}
</script>

<style scoped>
.uploadfile {
  display: flex;
  justify-content: left;
  align-items: center;
}
</style>
